<template>
  <!-- 逻辑：在这个页面获取数据，通过props传参的方式给各个组件传参 -->
  <div class="report">
    <tableTool>
      <div slot="export">
        <el-button type="primary" @click="excelExport">导出</el-button>
      </div>
      <div class="tool-form" slot="form">
        <div class="input-group">
          <span class="lable">设备名称：</span>
          <el-input placeholder="请输入" v-model="filterEquipmentName" />
        </div>
        <div class="input-group">
          <span class="lable">设备类别：</span>
          <el-input placeholder="请输入" v-model="filterCategoryName" />
        </div>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="success" @click="onReset">重置</el-button>
      </div>
    </tableTool>
    <customTable :list="list" :combined="combined">
      <template v-slot:title>
        <tr>
          <th colspan="14">{{ orgName }}</th>
        </tr>
        <tr>
          <th rowspan="2">设备编号</th>
          <th rowspan="2">设备名称</th>
          <th rowspan="2">规格型号</th>
          <th rowspan="2">操作人员</th>
          <th rowspan="2">原值（元）</th>
          <th colspan="2">工作量</th>
          <th rowspan="2">运行台班数</th>
          <th colspan="3">燃油核算</th>
          <th colspan="3">维修保养费核算</th>
        </tr>
        <tr>
          <th>开始日期</th>
          <th>结束日期</th>
          <th>实际燃油数量（L）</th>
          <th>定额油耗（L/台班）</th>
          <th>盈亏比列%</th>
          <th>实际维保费（元）</th>
          <th>维保定额（元/台班）</th>
          <th>盈亏比列%</th>
        </tr>
      </template>
      <template #body="{ list }">
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.equipmentNumber }}</td>
          <td>{{ item.equipmentName }}</td>
          <td>{{ item.equipmentStandard }}</td>
          <td>{{ item.operator }}</td>
          <td>{{ item.originalValue }}</td>
          <td>{{ item.startDate }}</td>
          <td>{{ item.endDate }}</td>
          <td>{{ item.runWorkShift }}</td>
          <td>{{ item.actualFuelQuantity }}</td>
          <td>{{ item.fixedFuel }}</td>
          <td>{{ item.profitLossRateFuel }}</td>
          <td>{{ item.actualMaintenance }}</td>
          <td>{{ item.fixedMaintenance }}</td>
          <td>{{ item.profitLossRateMaintenance }}</td>
        </tr>
      </template>
      <template #empty>
        <tr>
          <td colspan="14" class="empty">暂无数据</td>
        </tr>
      </template>
      <template #footer="{ combined }">
        <tr>
          <td>合计</td>
          <td>{{ combined.equipmentName }}</td>
          <td>{{ combined.equipmentStandard }}</td>
          <td>{{ combined.operator }}</td>
          <td>{{ combined.originalValue }}</td>
          <td>{{ combined.startDate }}</td>
          <td>{{ combined.endDate }}</td>
          <td>{{ combined.runWorkShift }}</td>
          <td>{{ combined.actualFuelQuantity }}</td>
          <td>{{ combined.fixedFuel }}</td>
          <td>{{ combined.profitLossRateFuel }}</td>
          <td>{{ combined.actualMaintenance }}</td>
          <td>{{ combined.fixedMaintenance }}</td>
          <td>{{ combined.profitLossRateMaintenance }}</td>
        </tr>
      </template>
    </customTable>
    <pagination @onCurrentChange="handleCurrentChange" :total="page.total"></pagination>
  </div>
</template>
<script>
import tableTool from '../components/tableTool.vue'
import customTable from '../components/customTable.vue'
import pagination from '../components/pagination.vue'
import { combinedFn, formatTime } from '@/pages/comprehensiveReport/equipmentManagement/mixin'
import request from '@/api/comprehensiveReport/equipmentManagement.js'
export default {
  name: 'singleMachineCostStatistics',
  components: { tableTool, customTable, pagination },
  data () {
    return {
      list: [],
      orgName: '',
      page: {
        total: 0,
        currentPage: 1,
        limit: 10,
      },
      combined: {},
      headers: {
        // 定义对应关系- 把英文的key转化成中文的key所对应的值
        设备编号: 'equipmentNumber',
        设备名称: 'equipmentName',
        规格型号: 'equipmentStandard',
        操作人员: 'operator',
        '原值（元）': 'originalValue',
        开始日期: 'startDate',
        结束日期: 'endDate',
        运行台班数: 'runWorkShift',
        '实际燃油数量（L）': 'actualFuelQuantity',
        '定额油耗（L/台班）': 'fixedFuel',
        '燃油盈亏比列%': 'profitLossRateFuel',
        '实际维保费（元）': 'actualMaintenance',
        '维保定额（元/台班）': 'fixedMaintenance',
        '维修盈亏比列%': 'profitLossRateMaintenance',
      },
      filterCategoryName: '',
      filterEquipmentName: ''
    }
  },
  created () {
    this.getList()
  },
  methods: {
    onSearch () {
      this.getList()
    },
    onReset () {
      this.filterCategoryName = ''
      this.filterEquipmentName = ''
      this.getList()
    },
    async getList () {
      this.orgName = this.$store.state.userInfo.orgInfo.orgName
      const data = await request.getEquipmentLightEngineCost({
        page: this.page.currentPage,
        limit: this.page.limit,
        orgId: localStorage.orgId,
        filterCategoryName: this.filterCategoryName,
        filterEquipmentName: this.filterEquipmentName
      })
      console.log('发送请求，获取数据', data)
      if (data.list.length == 0) {
        this.list = []
        this.combined = {}
        this.page.total = 0
        return;
      }
      this.page.total = data.totalCount
      const { list, combined } = combinedFn(Object.values(this.headers).slice(1), data.list, [
        'originalValue',
        'runWorkShift',
        'actualFuelQuantity',
        'fixedFuel',
        'actualMaintenance',
        'fixedMaintenance',
      ])
      this.list = formatTime(['startDate', 'endDate'], list)
      this.combined = combined
    },
    handleCurrentChange (currentPage) {
      this.page.currentPage = currentPage
      this.getList()
    },
    excelExport () {
      const multiHeader = [
        [this.orgName, '', '', '', '', '', '', '', '', '', '', '', '', ''],
        [
          '设备编号',
          '设备名称',
          '规格型号',
          '操作人员',
          '原值（元）',
          '工作量',
          '',
          '运行台班数',
          '燃油核算',
          '',
          '',
          '维修保养费核算',
          '',
          '',
        ],
      ] // 它是一个二维数组
      const merges = ['A1:N1', 'F2:G2', 'I2:K2', 'L2:N2', 'P2:Q2', 'A2:A3', 'B2:B3', 'C2:C3', 'D2:D3', 'E2:E3', 'H2:H3']
      // 懒加载 script-loader
      import('@/utils/Export2Excel.js').then(async (excel) => {
        // 获取所有的数据
        const res = await request.getEquipmentLightEngineCost({
          page: 1,
          limit: this.page.total,
          orgId: localStorage.orgId,
        })
        const list = formatTime(['startDate', 'endDate'], res.list)
        // list就是所有的数据，list [{},{},{}] 转换为 => [[],[],[],[]]
        const data = this.formatJson(this.headers, list) // 转化数据表结构
        const { combined } = combinedFn(Object.values(this.headers).slice(1), list, [
          'originalValue',
          'runWorkShift',
          'actualFuelQuantity',
          'fixedFuel',
          'actualMaintenance',
          'fixedMaintenance',
        ])
        data.push(['合计', ...Object.values(combined)])
        excel.export_json_to_excel({
          header: [
            '',
            '',
            '',
            '',
            '',
            '开始日期',
            '结束日期',
            '',
            '实际燃油数量（L）',
            '定额油耗（L/台班）',
            '盈亏比列%',
            '实际维保费（元）',
            '维保定额（元/台班）',
            '盈亏比列%',
          ],
          data,
          filename: '设备管理-单机（车）成本统计简表-' + this.orgName,
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges,
        })
      })
    },
    formatJson (headers, list) {
      return list.map((item) => {
        return Object.values(headers).map((value) => {
          return item[value]
        })
      })
    },
  },
}
</script>
<style lang="scss">

</style>
